package com.authentication;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.weaver.ast.Var;
import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SimpleOauth2RequestRepository implements AuthorizationRequestRepository<OAuth2AuthorizationRequest> {

    public static final String AUTHORIZATION_REQUEST = "authorizationRequest";
    private final Map<String, OAuth2AuthorizationRequest> map = new ConcurrentHashMap<>();


    @Override
    public OAuth2AuthorizationRequest loadAuthorizationRequest(HttpServletRequest request) {
        return null;
    }

    /**
     * 把 {@link OAuth2AuthorizationRequest} 设置到 request 的 cookie 或者 session 中
     * 注意 cookie 的有效路径
     *
     * @param authorizationRequest
     * @param request
     * @param response
     */
    @Override
    public void saveAuthorizationRequest(OAuth2AuthorizationRequest authorizationRequest, HttpServletRequest request, HttpServletResponse response) {
//      开始 oauth2 授权的时候
//      client 会为 授权请求设置一个 state 来标记这个请求
        String state = authorizationRequest.getState();

        /*byte[] encode = Base64.getEncoder().encode(ObjectUtil.serialize(authorizationRequest));
        Cookie cookie = new Cookie(AUTHORIZATION_REQUEST, new String(encode));
        // 必须把 cookie 设置为根路径，因为浏览器下次使用 code 来交换 token的时候路径和这一次不一样
        cookie.setPath("/");

        response.addCookie(cookie);*/


        map.put(state,authorizationRequest);
    }


    @Override
    public OAuth2AuthorizationRequest removeAuthorizationRequest(HttpServletRequest request) {

//      当 user 操作 authorization server 并同意 授权给 client 时
//      authorization server 把用户重定向回 client
//      重定向的时候就附带了 之前生成的 state
        String state = request.getParameter("state");

//      client 通过 authorization server 返回 的 state
//      找出 client 自己曾经发起过的 oauth2 授权请求信息

        return map.remove(state);

        /*for (Cookie cookie : request.getCookies()) {
            if (AUTHORIZATION_REQUEST.equals(cookie.getName())) {
                byte[] decode = Base64.getDecoder().decode(cookie.getValue());
                //TODO 解决反序列化失败
                return ObjectUtil.deserialize(decode, OAuth2AuthorizationRequest.class);
            }
        }
        return null;*/
    }
}
